<style>
  .outer {
    position: relative;
    height: 460px;
  }
  .toolbar {
    width: 100%;
    /* border: 1px solid #ccc; */
    position: relative;
    z-index: 125;
  }
  .text {
    border: 1px solid #ccc;
    /* min-height: 400px; */
    height: 400px;
  }
  .boxerl {
    position: relative;
    width: 100%;
    overflow-x: hidden;
    overflow-y: hidden;
    height: 320px;
  }
  .boxerh {
    z-index: 120;
    top: 66px;
    position: absolute;
    width: 100%;
    height: 400px;
    overflow-y: auto;
    overflow-x: hidden;
  }
  .scollbar {
    width: 100%;
    overflow-x: auto;
  }
  .blankinner {
    width: 768px;
    height: 5px;
    border: 1px solid white;
  }
</style>

<template>
  <div>
    <Modal
      :value="modalState"
      :title="title"
      :loading="loading"
      ok-text="保存"
      @on-ok="handleSubmit"
      @on-cancel="cancel"
      width="50%">
      <Form
        ref="goodPointsModal"
        :model="row"
        :rules="rules"
        style="width: 100%; margin-left: 50px;"
        :label-width="100">
        <FormItem prop="name" style="width: 300px;" label="商品名称：">
          <!-- <Select v-model="row.name" placeholder="请选择商品" :disabled="row.state === 1 ? true : false">
            <Option v-for="item in goodsList" :value="item.name" :key="item.id">
              {{ item.name }}
            </Option>
          </Select> -->
          <Input type="text" v-model="row.name" placeholder="请输入商品名称" />
        </FormItem>
        <FormItem prop="des" label="商品描述：" style="width: 400px">
          <Input type="textarea" :rows="4" v-model="row.des" placeholder="请输入商品描述" />
        </FormItem>
        <FormItem prop="img" label="商品图片：" style="width: 80%">
          <upload-img @upload-success="handleUpload" :folder="folder" :row="row"></upload-img>
        </FormItem>
        <FormItem prop="type" style="width: 300px;" label="兑换类型：">
          <Select v-model="row.type" placeholder="请选择兑换类型" >
            <Option value="0">
              商品兑换
            </Option>
            <Option value="1">
              现金兑换
            </Option>
          </Select>
        </FormItem>
        <!-- <FormItem prop="time" label="生效日期：" style="width: 300px">
          <DatePicker :disabled="row.state === 1 ? true : false" v-model="row.time" format="yyyy-MM-dd" type="daterange" style="width: 100%" placeholder="请选择起始时间"></DatePicker>
        </FormItem> -->
        <FormItem prop="score" label="兑换积分：" style="width: 300px">
          <Input type="text" v-model="row.score" placeholder="请输入兑换积分" />
        </FormItem>
        <FormItem prop="price" :label="row.type === '1' ? '兑换金额：':'商品原价：'" style="width: 300px">
          <Input type="text" v-model="row.price" :placeholder="row.type === '1' ? '请输入兑换金额' : '请输入商品原价'" />
        </FormItem>
        <FormItem prop="etime" label="结束时间：" style="width: 300px">
          <DatePicker v-model="row.etime" type="date" style="width: 100%" placeholder="请选择结束时间"></DatePicker>
        </FormItem>
        <FormItem prop="content" label="拼团内容：" style="width: 95%">
            <!-- <Input :disabled="row.state === 1" v-model="row.des" type="textarea" placeholder="请输入任务要求" /> -->
            <!-- <div ref="editor" style="text-align:left;">
            </div> -->
            <div class="outer">
              <div id="scoller" class="scollbar" @scroll="doThis()">
                <div class="blankinner"></div>
              </div>
              <div id="inner" class="boxerl">
                <div id="div1" class="toolbar">
                  <Button icon="md-trash" size="large" style="border: none; margin-top: -3px" @click="handleClear"></Button>
                </div>
              </div>
              <!--<div style="padding: 5px 0; color: #ccc">menu list</div>-->
              <div class="boxerh">
                <div id="div2" class="text">
                  <!--可使用 min-height 实现编辑区域自动增加高度-->
                  <!-- <p>请输入内容</p> -->
                </div>
              </div>
            </div>
          </FormItem>
        <!-- <FormItem prop="topState" label="是否置顶：" style="width: 300px">
          <i-switch v-model="row.topState" />
        </FormItem> -->
      </Form>
    </Modal>
  </div>
</template>
<script>
import {
  mapActions,
  mapState
} from 'vuex'
import UploadImg from '_c/upload-img'
import { getToken } from '../../libs/util'
import E from 'wangeditor'
export default {
  name: 'GoodPointsModal',
  components: {
    UploadImg
  },
  data () {
    const reg = /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/
    const scoreReg = /^\d+$/
    const validateMoney = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('金额不能为空!'))
      } else {
        if (!reg.test(value)) {
          callback(new Error('请输入正确的金额！'))
        } else {
          callback()
        }
      }
    }

    const validateScore = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('积分不能为空!'))
      } else {
        if (!scoreReg.test(value)) {
          callback(new Error('请输入正确的积分！'))
        } else {
          callback()
        }
      }
    }

    return {
      title: '',
      imgUrl: '',
      time: [],
      loading: true,
      folder: 'goodPoints',
      token: getToken(),
      rules: {
        name: [
          {
            required: true,
            message: '商品名称不能为空',
            trigger: 'blur'
          }
        ],
        type: [
          {
            required: true,
            message: '请选择兑换类型',
            trigger: 'change'
          }
        ],
        score: [
          {
            validator: validateScore,
            trigger: 'blur'
          }
        ],
        price: [
          {
            validator: validateMoney,
            trigger: 'blur'
          }
        ],
        etime: [
          {
            required: true,
            message: '请选择结束时间',
            trigger: 'change',
            type: 'date'
          }
        ]
      }
    }
  },
  updated () {
    if (this.row.id && this.row.id !== '') {
      this.title = '编辑积分商品'
    } else {
      this.title = '添加积分商品'
    }
  },
  computed: {
    ...mapState({
      row: state => state.goodPoints.row,
      modalState: state => state.modal.modalState
    })
  },
  methods: {
    ...mapActions(['updateModalState']),
    changeLoading () {
      this.loading = false
      this.$nextTick(() => {
        this.loading = true
      })
    },
    handleClear () {
      this.editor.txt.clear()
    },
    doThis () {
      var elem = document.getElementById('scoller')
      var inner = document.getElementById('inner')
      inner.scrollLeft = elem.scrollLeft
    },
    handleSubmit () {
      this.$refs.goodPointsModal.validate((valid) => {
        if (!valid) {
          return this.changeLoading()
        }
        this.$emit('good-points-valid', {
          id: this.row.id,
          name: this.row.name,
          des: this.row.des,
          type: this.row.type,
          price: this.row.price,
          score: this.row.score,
          etime: this.row.etime ? this.$moment(this.row.etime).format('YYYY-MM-DD') : '',
          // btime: (this.row.time && this.row.time[0]) ? this.$moment(this.row.time[0], this.$moment.ISO_8601).format('YYYY-MM-DD') : '',
          // etime: (this.row.time && this.row.time[1]) ? this.$moment(this.row.time[1], this.$moment.ISO_8601).format('YYYY-MM-DD') : '',
          img: this.row.img,
          content: this.editorContent ? this.editorContent : this.row.content
          // top: this.row.topState === true ? 1 : undefined
          // state: this.row.openState === true ? 0 : 1
        })
      })
    },
    cancel () {
      this.row.img = ''
      this.updateModalState(false)
      this.$refs['goodPointsModal'].resetFields()
    },
    handleUpload (url) {
      this.row.img = url
    }
  },
  created () {
    window.addEventListener('scroll', this.doThis)
  },
  mounted () {
    let self = this
    // //console.log(this.graphicList)
    this.actionUrl = process.env.NODE_ENV === 'development' ? '/api/upload?folder=goodPoints' : 'http://rbackapi.baisha.work/upload?folder=goodPoints'
    this.editor = new E('#div1', '#div2')
    // this.editor = new E(this.$refs.editor)
    this.editor.customConfig.onchange = (html) => {
      this.editorContent = html
      // this.$refs.showContent.innerHTML = html
    }
    // //console.log(this.row.content)
    // editor.customConfig.uploadImgShowBase64 = true
    this.editor.customConfig.withCredentials = true
    // this.editor.customConfig.debug = true
    this.editor.customConfig.uploadImgServer = this.actionUrl
    this.editor.customConfig.uploadImgMaxSize = 500 * 1024
    this.editor.customConfig.uploadImgHeaders = {
      'agent': 'Web',
      'token': this.token
    }
    // editor.customConfig.uploadImgParams = {
    //   // 如果版本 <=v3.1.0 ，属性值会自动进行 encode ，此处无需 encode
    //   // 如果版本 >=v3.1.1 ，属性值不会自动 encode ，如有需要自己手动 encode
    //   token: 'abcdef12345'
    // }
    this.editor.customConfig.uploadImgHooks = {
      before (xhr, editor, files) {
        // 图片上传之前触发
        // xhr 是 XMLHttpRequst 对象，editor 是编辑器对象，files 是选择的图片文件

        // 如果返回的结果是 {prevent: true, msg: 'xxxx'} 则表示用户放弃上传
        // return {
        //     prevent: true,
        //     msg: '放弃上传'
        // }
      },
      success (xhr, editor, result) {
        // 图片上传并返回结果，图片插入成功之后触发
        // xhr 是 XMLHttpRequst 对象，editor 是编辑器对象，result 是服务器端返回的结果
        // //console.log(editor)
        // //console.log(result)
      },
      fail (xhr, editor, result) {
        this.$Notice.warning({
          title: '文件大小不正确',
          desc: '请上传3M以下大小的图片'
        })
        // 图片上传并返回结果，但图片插入错误时触发
        // xhr 是 XMLHttpRequst 对象，editor 是编辑器对象，result 是服务器端返回的结果
      },
      error (xhr, editor) {
        // 图片上传出错时触发
        // xhr 是 XMLHttpRequst 对象，editor 是编辑器对象
      },
      timeout (xhr, editor) {
        // 图片上传超时时触发
        // xhr 是 XMLHttpRequst 对象，editor 是编辑器对象
      },

      // 如果服务器端返回的不是 {errno:0, data: [...]} 这种格式，可使用该配置
      // （但是，服务器端返回的必须是一个 JSON 格式字符串！！！否则会报错）
      customInsert (insertImg, result, editor) {
        // 图片上传并返回结果，自定义插入图片的事件（而不是编辑器自动插入图片！！！）
        // insertImg 是插入图片的函数，editor 是编辑器对象，result 是服务器端返回的结果

        // 举例：假如上传图片成功后，服务器端返回的是 {url:'....'} 这种格式，即可这样插入图片：
        let url = result.host + result.data
        insertImg(url)
        // result 必须是一个 JSON 格式字符串！！！否则报错
      }
    }
    this.editor.customConfig.customAlert = function (info) {
      // info 是需要提示的内容
      self.$Notice.warning({
        title: '文件大小不正确',
        desc: '请上传500kb以下大小的图片'
      })
    }
    this.editor.customConfig.pasteFilterStyle = false
    this.editor.create()
    this.editor.txt.html(this.row.content)
    // if (this.row.state === 1) {
    //   this.editor.$textElem.attr('contenteditable', false)
    // }
  }
}
</script>
